<template>
  <div class="register">
    <div class="register-msg">
      <p class="register-msg-welconme">欢迎登录</p>
      <div class="register-msg-line"></div>
      <div class="register-msg-title">
        <img src="@/assets/img/register/logo_title.png" alt="" />
      </div>
    </div>
    <!-- 注册窗口 -->
    <div class="register-form">
      <div class="register-form-con">
        <el-tabs v-model="activeName" class="register-form-con-tabs" @tab-click="handleClick">
          <el-tab-pane label="单位注册" name="company"></el-tab-pane>
          <el-tab-pane label="个人注册" name="personal"></el-tab-pane>
        </el-tabs>
        <!-- 单位注册 -->
        <div class="register-form-con" v-if="activeName === 'company'">
          <el-form
            size="small"
            ref="formCompanyFrom"
            :model="formCompany.form"
            :rules="formCompany.rules"
            label-width="75px"
          >
            <el-form-item label="单位名称" prop="name">
              <el-input v-model.trim="formCompany.form.name" placeholder="请输入单位名称" clearable> </el-input>
            </el-form-item>
            <el-form-item label="申请人" prop="apply_user">
              <el-input
                v-model.trim="formCompany.form.apply_user"
                placeholder="请输入申请人姓名"
                maxLength="40"
                clearable
              >
              </el-input>
            </el-form-item>
            <el-form-item label="申请电话" prop="apply_mobile">
              <el-input
                v-model.trim="formCompany.form.apply_mobile"
                placeholder="请输入申请电话"
                maxLength="40"
                clearable
              >
              </el-input>
            </el-form-item>
          </el-form>
          <div class="register-form-con-export">
            <div class="register-form-con-export-pic">
              <div class="register-form-con-export-pic-left">
                <el-image
                  style="width: 100px; height: 100px"
                  v-if="formCompany.excelImg"
                  :src="formCompany.excelImg"
                  :preview-src-list="formCompany.imgApplyList"
                  fit="cover"
                />
                <img v-else src="@/assets/img/register/pic_1.png" alt="" />
              </div>
              <div class="register-form-con-export-pic-right">
                <el-image
                  style="width: 100px; height: 100px"
                  v-if="formCompany.CardImg"
                  :src="formCompany.CardImg"
                  :preview-src-list="formCompany.imgCardList"
                  fit="cover"
                />
                <img v-else src="@/assets/img/register/pic_2.png" alt="" />
              </div>
              <div @click="clickGuide" class="register-form-con-export-pic-tips">上传注意事项</div>
            </div>
            <div class="register-form-con-export-upload">
              <el-upload
                action="#"
                :auto-upload="false"
                accept="image/jpeg,image/gif,image/png"
                :on-change="formCompany.uploadExcel"
              >
                <p style="margin-right: 53px">上传《申请表》</p>
              </el-upload>
              <el-upload
                action="#"
                :auto-upload="false"
                accept="image/jpeg,image/gif,image/png"
                :on-change="formCompany.uploadCopyCard"
              >
                <p>上传身份证复印件</p>
              </el-upload>
            </div>
          </div>
          <div class="register-form-agreement">
            <input type="checkbox" :checked="checkAgreement" @click="clickChecked" />
            <p>已阅读并同意青海无人机综合管理服务平台<span>《用户协议》</span></p>
          </div>
        </div>
        <!-- 个人注册 -->
        <div class="register-form-con-personal" v-if="activeName === 'personal'">
          <el-form
            size="small"
            ref="formPersonalFrom"
            :model="formPersonal.form"
            :rules="formPersonal.rules"
            label-width="75px"
          >
            <el-form-item label="账号" prop="mobile">
              <el-input v-model="formPersonal.form.mobile" placeholder="请输入手机号" maxLength="40" clearable>
              </el-input>
            </el-form-item>
            <el-form-item label="账号名称" prop="name">
              <el-input v-model.trim="formPersonal.form.name" placeholder="请输入用户名" maxLength="40" clearable>
              </el-input>
            </el-form-item>
            <el-form-item label="所属单位" prop="company">
              <el-select
                v-model="formPersonal.form.company"
                filterable
                remote
                :remote-method="remoteMethod"
                placeholder="请选择单位"
                size="large"
              >
                <el-option v-for="item in companyList" :key="item.id" :label="item.unit_name" :value="item.id" />
              </el-select>
            </el-form-item>
            <el-form-item label="密码" prop="password">
              <el-input
                v-model.trim="formPersonal.form.password"
                placeholder="请输入密码"
                type="password"
                maxLength="40"
                clearable
              >
              </el-input>
            </el-form-item>
            <el-form-item label="确认密码" prop="rePassword">
              <el-input
                v-model.trim="formPersonal.form.rePassword"
                placeholder="请再次输入密码"
                type="password"
                maxLength="40"
                clearable
              >
              </el-input>
            </el-form-item>
            <el-form-item label="验证码" prop="sms_code" style="margin-bottom: 15px">
              <div class="register-form-con-code">
                <el-input
                  v-model.trim="formPersonal.form.sms_code"
                  placeholder="请输入验证码"
                  maxLength="40"
                  class="register-form-con-code-input"
                />
                <el-button @click="getCode" :disabled="!codeFlag">
                  <span v-show="!codeFlag">{{ `${time}秒后重新获取` }}</span>
                  <span v-show="codeFlag">获取验证码</span>
                </el-button>
              </div>
            </el-form-item>
            <div class="register-form-agreement">
              <input type="checkbox" :checked="checkAgreement" @click="clickChecked" />
              <p>已阅读并同意青海无人机综合管理服务平台<span>《用户协议》</span></p>
            </div>
          </el-form>
        </div>
      </div>
      <!--按钮 -->
      <div class="register-form-btn" :style="activeName === 'personal' ? 'margin-top: 35px;' : 'margin-top: 20px;'">
        <div class="register-form-btn-apply" @click="clickApply">
          {{ activeName === 'personal' ? '注册' : '发起申请' }}
        </div>
        <div @click="clickLogin" class="register-form-btn-login">
          {{ activeName === 'personal' ? '个人登录' : '单位登录' }}
        </div>
      </div>
      <!-- 单位注册页底部 -->
      <div>
        <div class="register-form-con-line"></div>
        <a
          href="/青海省无人机综合服务管理平台注册审核表.docx"
          download="青海省无人机综合服务管理平台注册审核表"
          class="register-form-con-down"
        >
          <img src="@/assets/img/register/icon_table.png" alt="" />
          <p>下载《申请表》</p>
        </a>
        <div class="register-form-con-tips">
          <p @click="clickGuide">如何进行单位注册？</p>
          <p style="width: 1px; height: 10px; background: #d8d8d8; margin: 15px"></p>
          <div class="register-form-con-tips-query" @click="clickQuery">
            <span>申请进度查询</span>
            <div class="register-form-con-tips-query-serach" v-show="queryShow">
              <p @click="queryCompany">单位注册申请进度查询</p>
              <p @click="queryPassword">单位找回密码申请进度查询</p>
            </div>
          </div>
        </div>
      </div>
    </div>
    <!-- 引导页弹窗 -->
    <comGuideDialog v-if="queryVisible" :examineVisible="queryVisible" @closeDialog="clickGuide"></comGuideDialog>
    <!-- 注册进度查询弹窗 -->
    <comExamineDialo v-if="registerQuery" :queryOpen="registerQuery" @closeDialog="queryCompany"></comExamineDialo>
    <!-- 密码进度查询弹窗 -->
    <comComanyPassword v-if="passwordQuery" :queryOpen="passwordQuery" @closeDialog="queryPassword"></comComanyPassword>
  </div>
</template>
<script lang="ts" setup>
import {ref, reactive, onMounted, onUnmounted} from 'vue';
import {useRouter, useRoute} from 'vue-router';
import {ElMessage} from 'element-plus';
import comGuideDialog from '@/components/comGuideDialog/index.vue';
import comExamineDialo from '@/components/comExamineDialo/index.vue';
import comComanyPassword from '@/components/comComanyPassword/index.vue';
import registerApi from '@/api/register.ts';
import {validatePassword, validateAccount} from '@/utils/validator.js';

const activeName = ref('company');
const registerQuery = ref(false); // 单位注册进度弹窗
const passwordQuery = ref(false); // 忘记密码进度弹窗
const queryVisible = ref(false); // 引导页弹窗
const companyList = ref([]); // 单位列表
const checkAgreement = ref(false); // 勾选协议状态
const codeFlag = ref(true);
const timer = ref(null);
const time = ref<number>(0);
const queryShow = ref(false);

const route = useRoute();
const router = useRouter();

// tab点击
const handleClick = () => {
  formCompany.form = {
    name: '',
    apply_user: '',
    apply_mobile: '',
  };
  formCompany.CardImg = '';
  formCompany.excelImg = '';
  formCompany.imgApplyList = [];
  formCompany.imgCardList = [];
  formPersonal.form = {
    mobile: '',
    name: '',
    company: '',
    password: '',
    rePassword: '',
  };
  checkAgreement.value = false;
};
// 勾选协议
const clickChecked = () => {
  checkAgreement.value = !checkAgreement.value;
};
// 查询进度
const clickQuery = () => {
  queryShow.value = !queryShow.value;
};
// 引导页弹窗
const clickGuide = () => {
  queryVisible.value = !queryVisible.value;
};
// 注册进度查询弹窗
const queryCompany = () => {
  registerQuery.value = !registerQuery.value;
};
// 密码进度弹窗
const queryPassword = () => {
  passwordQuery.value = !passwordQuery.value;
};
// 获取所属单位列表
const getCompanyList = () => {
  registerApi
    .getCompanyList()
    .then((res) => {
      companyList.value = res.data;
    })
    .catch((err) => {
      throw err;
    });
};
// 搜索单位列表
const remoteMethod = (query: string) => {
  if (query) {
    registerApi
      .getCompanyList({keyword: query})
      .then((res) => {
        companyList.value = res.data;
      })
      .catch((err) => {
        throw err;
      });
  } else {
    companyList.value = [];
  }
};
// 获取验证码
const getCode = () => {
  if (!formPersonal.form.mobile) {
    ElMessage.warning('请先输入手机号');
    return;
  }
  if (/^1[3456789]\d{9}$/.test(formPersonal.form.mobile)) {
    registerApi
      .getMsgCode({mobile: formPersonal.form.mobile, action: 'register'})
      .then((res) => {
        if (res.status === 0) {
          ElMessage.success(res.message);
          timeCountdown();
        } else {
          ElMessage.error(res.message);
        }
      })
      .catch((err) => {
        throw err;
      });
  } else {
    ElMessage.error('手机号码格式不正确');
  }
};
// 定时器
const timeCountdown = () => {
  const TIME_COUNT = 60;
  if (!timer.value) {
    time.value = TIME_COUNT;
    codeFlag.value = false;
    timer.value = setInterval(() => {
      if (time.value > 0 && time.value <= TIME_COUNT) {
        time.value--;
      } else {
        codeFlag.value = true;
        clearInterval(timer.value);
        timer.value = null;
      }
    }, 1000);
  }
};
// 个人注册校验
const formPersonalFrom = ref(null);
const formPersonal = reactive({
  form: {mobile: '', name: '', company: '', password: '', rePassword: ''},
  rules: {
    mobile: [{validator: validateAccount, trigger: 'blur'}],
    name: [{required: true, message: '请输入用户名', trigger: 'blur'}],
    company: [{required: true, message: '请选择单位', trigger: 'change'}],
    password: [{validator: validatePassword, trigger: 'blur'}],
    rePassword: [{validator: validatePassword, trigger: 'blur'}],
    sms_code: [{required: true, message: '请输入验证码', trigger: 'blur'}],
  },
});
// 单位注册校验
const formCompanyFrom = ref(null);
const formCompany = reactive({
  form: {
    name: '',
    apply_user: '',
    apply_mobile: '',
  },
  rules: {
    name: [{required: true, message: '请输入单位名称', trigger: 'blur'}],
    apply_user: [{required: true, message: '请输入申请人姓名', trigger: 'blur'}],
    apply_mobile: [{validator: validateAccount, trigger: 'blur'}],
  },
  CardImg: '',
  excelImg: '',
  imgApplyList: [], // 申请表大图
  imgCardList: [], // 身份证大图
  // 上传身份证复印件
  uploadCopyCard: (res) => {
    registerApi
      .uploadImg({file: res.raw, type: 'unit_register'})
      .then((data) => {
        formCompany.CardImg = data.data;
        formCompany.imgCardList.push(data.data);
      })
      .catch((err) => {
        throw err;
      });
  },
  // 上传申请表
  uploadExcel: (res) => {
    registerApi
      .uploadImg({file: res.raw, type: 'unit_register'})
      .then((data) => {
        formCompany.excelImg = data.data;
        formCompany.imgApplyList.push(data.data);
      })
      .catch((err) => {
        throw err;
      });
  },
});

// 发起申请
const clickApply = debounce(() => {
  let params;
  if (activeName.value === 'company') {
    formCompanyFrom.value.validate((valid) => {
      if (valid) {
        if (!formCompany.CardImg && !formCompany.excelImg) {
          ElMessage.error('请上传申请表和身份证复印件');
          return;
        }
        if (!checkAgreement.value) {
          ElMessage.error('请先勾选用户协议');
          return;
        }
        params = {
          name: formCompany.form.name,
          apply_user: formCompany.form.apply_user,
          apply_mobile: formCompany.form.apply_mobile,
          apply_table_file_url: formCompany.excelImg,
          apply_id_card_file_url: formCompany.CardImg,
        };
        registerApi
          .companyRegister(params)
          .then((res) => {
            if (res.status === 0) {
              ElMessage.success(res.message);
            }
          })
          .catch((err) => {
            throw err;
          });
      }
    });
  } else {
    formPersonalFrom.value.validate((valid) => {
      if (valid) {
        if (formPersonal.form.password !== formPersonal.form.rePassword) {
          ElMessage.error('两次输入的密码不一致！');
          return;
        }
        if (!checkAgreement.value) {
          ElMessage.error('请先勾选用户协议');
          return;
        }
        params = {
          mobile: formPersonal.form.mobile,
          name: formPersonal.form.name,
          password: formPersonal.form.password,
          unit_id: formPersonal.form.company.toString(),
          sms_code: formPersonal.form.sms_code,
        };
        registerApi
          .personalRegister(params)
          .then((res) => {
            if (res.status === 0) {
              router.push({
                name: 'login',
                params: {
                  activeName: 'personal',
                  mobile: formPersonal.form.mobile,
                },
              });
              ElMessage.success(res.message);
            }
          })
          .catch((err) => {
            throw err;
          });
      }
    });
  }
}, 1000);

// 防抖
function debounce(func, wait) {
  let timeout;
  return function (...args) {
    if (timeout) clearTimeout(timeout);
    const isTime = !timeout;
    timeout = setTimeout(() => {
      timeout = null;
    }, wait);
    if (isTime) func.apply(this, args);
  };
}

// 登录
const clickLogin = () => {
  if (activeName.value === 'company') {
    router.push({name: 'login', params: {activeName: 'company'}});
  } else {
    router.push({name: 'login', params: {activeName: 'personal'}});
  }
};
onMounted(() => {
  if (route.params.activeName) {
    activeName.value = route.params.activeName;
  } else {
    activeName.value = 'personal';
  }
  getCompanyList();
});
onUnmounted(() => {
  clearInterval(timer.value);
});
</script>

<style lang="scss" scoped>
.register {
  width: 100%;
  height: 100%;
  background: url(@/assets/img/login/login_bg.png);
  background-repeat: no-repeat;
  background-size: 100%;
  background-position: center center;
  position: relative;
  &-msg {
    position: absolute;
    top: 20.3%;
    left: 12.76%;
    color: #8fb4fe;
    width: 576px;
    overflow: hidden;
    &-welconme {
      font-size: 30px;
      color: #ffffff;
      font-weight: 600;
    }
    &-line {
      width: 248px;
      height: 2px;
      background: #d8d8d8;
    }
    &-title {
      width: 576px;
      margin: 31px 0 41px 0;
      font-size: 48px;
      color: #ffffff;
      > img {
        width: 100%;
      }
    }
  }
  &-form {
    position: absolute;
    top: 8.15%;
    right: 13.28%;
    width: 522px;
    background: #ffffff;
    border-radius: 10px;
    margin-left: 10.83%;
    padding: 46px 0 50px;
    &-con {
      overflow: hidden;
      display: flex;
      flex-direction: column;
      align-items: center;
      &-tabs {
        display: flex;
        justify-content: center;
      }
      &:deep(.el-tabs__nav-wrap) {
        &::after {
          position: static !important;
        }
      }
      &:deep(.el-tabs__item) {
        font-size: 22px;
        color: #999999;
      }
      &:deep(.is-active) {
        color: #333333;
        font-weight: bold;
        font-size: 22px;
      }
      &:deep(.el-tabs__active-bar) {
        width: 40px !important;
        height: 4px;
        position: absolute;
        left: 24px;
        background: #1182fb;
        border-radius: 6px;
      }
      .el-form-item {
        margin-top: 25px;
      }
      .el-input {
        width: 280px;
      }
      .el-select {
        width: 280px;
        &:deep(.el-input--suffix) {
          width: 280px;
        }
      }
      &:deep(.el-input__wrapper) {
        background: #f2f4f9;
      }
      &:deep(.el-form-item__label) {
        text-align: left !important;
      }
      &:deep(.el-input__wrapper) {
        box-shadow: none !important;
      }
      &:deep(.el-form-item.is-required:not(.is-no-asterisk) > .el-form-item__label:before) {
        display: none;
      }
      &:deep(.el-upload-list) {
        display: none;
      }
      &-export {
        height: 295px;
        margin-top: 21px;
        background: #f2f4f9;
        overflow: hidden;
        &-pic {
          display: flex;
          justify-content: center;
          position: relative;
          padding-top: 20px;
          &-left,
          &-right {
            width: 241px;
            height: 173px;
            background: #f2f4f9;
            flex: 1;
            display: flex;
            align-items: center;
            justify-content: center;
            > img {
              width: 100%;
              height: 100%;
            }
            &-tips {
              position: absolute;
              top: 83px;
              left: -37px;
              width: 85px;
              height: 57px;
              background: #3369f4;
              border-radius: 4px;
              color: #fff;
              font-size: 13px;
              padding: 0 15px;
              padding-top: 10px;
              box-sizing: border-box;
              > p {
                margin: 0;
              }
            }
          }
          &-tips {
            position: absolute;
            top: 6.09%;
            right: 0;
            width: 95px;
            height: 27px;
            background: #ffffff;
            border-radius: 15px 0px 0px 15px;
            opacity: 0.8;
            font-size: 8px;
            line-height: 27px;
            text-align: center;
            cursor: pointer;
          }
        }
        &-upload {
          display: flex;
          margin-top: 30px;
          margin-bottom: 16px;
          justify-content: center;
          p {
            width: 140px;
            height: 40px;
            border-radius: 4px;
            border: 2px solid #3369f4;
            line-height: 40px;
            margin: 0;
            text-align: center;
            font-size: 14px;
            color: #3369f4;
            cursor: pointer;
          }
          > span {
            font-size: 14px;
            color: #3369f4;
            text-decoration: underline;
            cursor: pointer;
          }
        }
      }
      &-line {
        width: 383px;
        border: 1px solid #dcdcdc;
        margin: 0 auto;
        margin-top: 25px;
      }
      &-down {
        width: 382px;
        height: 40px;
        display: flex;
        justify-content: center;
        align-items: center;
        border-radius: 20px;
        margin: 0 auto;
        margin-top: 30px;
        border: 2px solid #cccccc;
        text-decoration: none;
        cursor: pointer;
        > img {
          width: 16px;
          height: 18px;
          margin-right: 20px;
        }
        > p {
          color: #333333;
          font-size: 14px;
        }
      }
      &-tips {
        display: flex;
        justify-content: center;
        align-items: center;
        > p {
          cursor: pointer;
          color: #3369f4;
        }
        > span {
          margin: 0 19px;
        }
        &-query {
          position: relative;
          cursor: pointer;
          color: #3369f4;
          &-serach {
            > p {
              margin: 0;
              padding: 5px 16px;
              &:hover {
                background: rgba(0, 0, 0, 0.04);
              }
            }
            position: absolute;
            top: 0;
            left: 110px;
            color: #333;
            width: 230px;
            background: #ffffff;
            box-shadow: 0px 2px 6px 0px rgba(0, 0, 0, 0.06), 0px 2px 6px 6px rgba(0, 0, 0, 0.02),
              0px -2px 4px 0px rgba(0, 0, 0, 0.02);
          }
        }
      }
      &-code {
        width: 280px;
        height: 36px;
        background: #f2f4f9;
        border-radius: 4px;
        display: flex;
        align-items: center;
        justify-content: space-between;
        .el-button {
          border: 0;
          margin: 0;
          color: #3369f4;
          font-size: 13px;
          background: #f2f4f9;
        }
      }
    }
    &-agreement {
      display: flex;
      margin: 0 auto;
      margin-top: 32px;
      > p {
        margin: 0;
        margin-left: 5px;
        font-size: 13px;
        color: #999;
        cursor: pointer;
        > span {
          cursor: pointer;
          color: #333;
        }
      }
    }
    &-btn {
      display: flex;
      flex-direction: column;
      &-apply,
      &-login {
        width: 382px;
        height: 40px;
        margin: 0 auto;
        border-radius: 4px;
        color: #333333;
        border: 0;
        text-align: center;
        cursor: pointer;
        line-height: 40px;
      }
      &-apply {
        background: #3369f4;
        color: #fff;
      }
    }
  }
}
</style>
